﻿////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// <copyright>Copyright 2008-2011 Andreas Huber Doenni</copyright>
// Distributed under the GNU General Public License version 2 (GPLv2).
// See accompanying file License.txt or copy at http://phuse.codeplex.com/license.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

namespace Phuse.Mime
{
    using System.IO;
    using System.Text;

    using Phuse.IO;

    /// <summary>Processes the body of a text entity.</summary>
    internal sealed class TextBodyProcessor : UnstructuredTextProcessor, ILineProcessor<Body>
    {
        private readonly bool deleteSpaceBeforeLineBreaks;
        private readonly TextBody result;

        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        /// <summary>See <see cref="ILineProcessor{T}.GetResult"/>.</summary>
        public Body GetResult()
        {
            this.result.Content = this.GetText();
            return this.result;
        }

        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        internal TextBodyProcessor(
            EncodingTransformation encodingTransformation,
            Encoding encoding,
            Disposition disposition,
            FallbackReason fallbackReason) :
            base(encodingTransformation, encoding)
        {
            this.result = new TextBody(fallbackReason) { Disposition = disposition, Format = Format.Fixed };
        }

        internal TextBodyProcessor(
            EncodingTransformation encodingTransformation,
            Encoding encoding,
            string subtype,
            Disposition disposition,
            Format format,
            bool deleteSpaceBeforeLineBreaks) :
            base(encodingTransformation, encoding)
        {
            this.deleteSpaceBeforeLineBreaks = deleteSpaceBeforeLineBreaks;
            this.result = new TextBody(subtype) { Disposition = disposition, Format = format };
        }

        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        /// <summary>See <see cref="UnstructuredTextProcessor.AddCustomTransformation"/>.</summary>
        protected sealed override Stream AddCustomTransformation(Stream content)
        {
            return this.result.Format == Format.Fixed ?
                content : new FlowedStream(content, this.deleteSpaceBeforeLineBreaks, false);
        }
    }
}
